import base64
import json
import os

import paramiko
from ftplib import FTP
from applications.configs.common import SSH_URL, SSH_PORT, SSH_USER, SSH_PASSWORD, FTP_URL, FTP_USER, FTP_PASSWORD, \
    V2RAY_CONFIG_FILE, FTP_LOCAL_FILE_PATH, V2RAY_URL


# 重启v2ray服务
def restart_v2ray_server():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # 连接到远程服务器
    client.connect(SSH_URL, SSH_PORT, SSH_USER, SSH_PASSWORD)

    # 运行v2ray命令
    stdin, stdout, stderr = client.exec_command('bash v2ray restart')
    stdout.channel.recv_exit_status()  # 等待命令执行完成

    output = stdout.read().decode('utf-8').strip()
    error = stderr.read().decode('utf-8').strip()
    print(output, error)
    # 关闭 SSH 连接
    client.close()


# v2ray 操作类
def get_ftp():
    ftp = FTP(FTP_URL)
    ftp.login(user=FTP_USER, passwd=FTP_PASSWORD)
    return ftp


class V2rayUtils:
    # 协议
    protocol = "vmess"

    # 生成协议连接
    def create_protocol_url(self, remark, user_id, path):
        json_config = json.dumps({
            "v": 2, "ps": remark, "add": V2RAY_URL, "port": "443",
            "id": user_id, "aid": "0", "net": "ws", "host": V2RAY_URL, "path": f"/{path}", "tls": "tls"
        })
        base64_config = base64.b64encode(json_config.encode('utf-8')).decode('utf-8')
        return f"{self.protocol}://{base64_config}"

    # 解析协议地址
    def parse_protocol_uri(self, protocol_str):
        # 移除前缀
        prefix = f"{self.protocol}://"
        if protocol_str.startswith(prefix):
            protocol_str = protocol_str.replace(prefix, "")

        # Base64解码
        decoded_bytes = base64.b64decode(protocol_str)
        decoded_str = decoded_bytes.decode('utf-8')
        return json.loads(decoded_str)

    # 读取配置文件
    def ftp_read_content(self):
        ftp = get_ftp()
        # 下载文件
        with open(FTP_LOCAL_FILE_PATH, 'wb') as local_file:
            # 写入文件
            ftp.retrbinary(f'RETR {V2RAY_CONFIG_FILE}', local_file.write)
            local_file.close()
        ftp.close()
        # 读取本地配置文件
        with open(FTP_LOCAL_FILE_PATH, 'r') as config_file:
            # 读取文件内容
            config_content = config_file.read()
            config_file.close()
        # 删除配文件
        if os.path.exists(FTP_LOCAL_FILE_PATH):
            os.remove(FTP_LOCAL_FILE_PATH)

        return json.loads(config_content)

    # 写入配置文件
    def ftp_write_content(self, content):
        # 写入本地问价
        with open(FTP_LOCAL_FILE_PATH, 'wb') as config_file:
            config_file.write(json.dumps(content, ensure_ascii=False).encode('utf-8'))
            config_file.close()

        # 写入ftp文件
        ftp = get_ftp()
        with open(FTP_LOCAL_FILE_PATH, 'rb') as file:
            ftp.storbinary(f'STOR {V2RAY_CONFIG_FILE}', file)
        ftp.close()

        # 删除配文件
        if os.path.exists(FTP_LOCAL_FILE_PATH):
            os.remove(FTP_LOCAL_FILE_PATH)

        # 同步服务
        restart_v2ray_server()